package com.qingzhuge.manager.controller;

import com.google.code.kaptcha.Producer;
import com.qingzhuge.common.utils.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author : zero.xiao
 * @description : 验证码
 * @date : 2018/6/22 0022 下午 12:22
 * @modified :
 * @since :
 */
@Api(tags = "验证码")
@RestController
@RequestMapping("api/sys/open")
public class CaptchaController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final Producer producer;

    @Autowired
    public CaptchaController(Producer producer) {
        this.producer = producer;
    }

    @ApiOperation(value = "验证码")
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        logger.info("生成文字验证码:{}", text);
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        image.setRGB(10, 10, 100);
        //保存到shiro session,建议存入redis中,待确认集群时的数据一致性
        WebUtil.setKaptcha(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }
}
